<?php
require("view_header.php");
// 1. 允许管理员进入该页面
$isAllowAccess = isset($_SESSION['administrator']);
// 2. 允许学校管理员添加账号
$isAllowAccess |= isset($_SESSION['xxadmin']);
if (!$isAllowAccess ){
    echo "<a href='../loginpage.php'>Please Login First!</a>";
    exit(1);
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf8">
    <title> 用户列表 </title>
</head>
<body>
<div class="container col-sm-12" id="user_list">
    <!--删除用户提示框-->
    <zz-modal-component
            v-if="delDlg.isShow"
            modal-title='删除用户'
            modal-style='width:300px;'
            ok-btn="确认"
            cancel-btn="取消"
            @on-ok="okDelUser"
            @on-cancel="cancelDelUser">
        <div slot="modal-content">
            <p>{{delDlg.tips}}</p>
        </div>
    </zz-modal-component>

    <!--导出用户用户提示框-->
    <zz-modal-component
            v-if="exportDlg.isShow"
            modal-title='用户导出'
            modal-style='width:500px;'
            ok-btn="确认"
            cancel-btn="取消"
            @on-ok="exportUser(true, false)"
            @on-cancel="exportUser(false, true)">
        <div slot="modal-content">
            <div>
                <div class="col-xs-12">
                    <p>请输入起始时间和结束时间</p>
                </div>
                <div class="col-xs-12">
                    起始时间：<input v-model="exportDlg.begin_date" class="span" size="16" type="text">
                    &nbsp;&nbsp;
                    结束时间：<input v-model="exportDlg.end_date" class="span" size="16" type="text">
                </div>
            </div>
        </div>
    </zz-modal-component>

    <div class="col-sm-12">
        <center><h3>用户管理</h3></center>
    </div>
    <div class="panel panel-default col-sm-12">
        <div class="panel-body">
        <form @submit.prevent="searchUser(true)" class="form-horizontal" >
            <div class="col-lg-12 col-lg-12">
                <div class="control-group col-lg-3 col-sm-3">
                    <input v-model="searchPara.keyword" class="form-control" placeholder="请输入用户名、姓名或校区" type="text">
                </div>
                <div class="control-group col-lg-3 col-sm-3">
                    <label class="col-sm-4">用户类型</label>
                    <div class="col-sm-8">
                        <select v-model="searchPara.type" class="form-control selectpicker">
                            <option value="-1" selected>不限</option>
                            <option value ="1">学生</option>
                            <option value ="2">老师</option>
                            <option value ="3">家长</option>
                        </select>
                    </div>
                </div>
                <div class="control-group col-lg-4 col-sm-4">
                    <label class="control-label col-sm-3">年级</label>
                    <div class="col-sm-9">
                        <select v-model="searchPara.gradeui" class="form-control selectpicker">
                            <option selected>不限</option>
                            <option v-for="grade in gradeList">
                                {{ grade }}
                            </option>
                        </select>
                    </div>
                </div>
                <div class="col-lg-2 col-sm-2">
                    <div class="control-group col-sm-8">
                        <input v-model="searchPara.classui" class="form-control" placeholder="输入数字" type="text">
                    </div>
                    <label style="margin-top: 0.5rem;">班</label>
                </div>
            </div>
            <div class="control-group col-sm-12 col-lg-12">
                <div class="col-sm-1 col-lg-1">
                    <button @click="switchPage(0)" type="button" class="btn btn-primary" >首页</button>
                </div>
                <div class="col-sm-1 col-lg-1">
                    <button @click="switchPage(-1)" type="button" class="btn btn-primary" >上一页</button>
                </div>
                <div class="col-sm-1 col-lg-1">
                    <button @click="switchPage(1)"  type="button" class="btn btn-primary" >下一页</button>
                </div>
                <div class="col-sm-1 col-lg-1">
                    <button @click="chooseAll()" type="button" class="btn btn-warning" >全选</button>
                </div>
                <div class="col-sm-1 col-lg-1">
                    <button @click="delUser(null)" type="button" class="btn btn-warning" >删除</button>
                </div>
                <div class="col-sm-1 col-lg-1">
                    <button @click="editUser(null)" type="button" class="btn btn-primary" >添加</button>
                </div>
                <div class="col-sm-1 col-lg-1">
                    <button @click="importUser()" type="button" class="btn btn-primary" >批量导入</button>
                </div>
                <div class="col-sm-2 col-lg-2">
                    <button @click="exportUser(false, false)" type="button" class="btn btn-primary" >批量导出</button>
                </div>
                <div class="col-sm-1 col-lg-1">
                    <button type="submit" class="btn btn-primary" >查找</button>
                </div>
                <div class="col-sm-1">
                    <button @click="resetSearchPara()" type="reset" class="btn btn-primary" >清空</button>
                </div>
            </div>
        </form>
        </div>
        <table class="table table-bordered">
            <thead>
            <tr>
                <th><input class="checkbox-default" v-model="isChoosedAll" type="checkbox" @click="chooseAll()"/></th>
                <th>ID<th>用户名<th>状态<th>用户类型<th>初中/高中<th>班级<th>校区</th>
                <th>创建时间<th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr	v-for="(user, index) in users" :key="index">
                <td><input class="checkbox-primary" v-model="user.ischoosed" type="checkbox" /></td>
                <td><a :href="userInfoUrl(user.id)">{{user.id}}</a></td>
                <td>{{user.name}}</td>
                <td>
                    <a :href="availableChgUrl(user.id, )">
                        <span v-if="user.available" class=green>已激活</span>
                        <span v-else class=red>已禁用</span>
                    </a>
                </td>
                <td>
                    <span v-if="user.type==1">学生</span>
                    <span v-else-if="user.type==2">老师</span>
                    <span v-else-if="user.type==3">家长</span>
                    <span v-else></span>
                </td>
                <td>{{user.gradestr}}</td>
                <td>
                    <span v-if="user.class <= 0"></span>
                    <span v-else>{{user.class}}班</span>
                </td>
                <td>{{user.school}}</td>
                <td>{{user.createtime}}</td>
                <td>
                    <div v-if="user.can_op == 1">
                        <button v-on:click="editUser(user)">编辑</button>
                        &nbsp;<button v-on:click="delUser(index)">删除</button>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</div>

<script>
    let app = new Vue({
        el: "#user_list",
        data:{
            // 搜索相关
            searchPara:{
                keyword: "",
                type: -1,
                gradeui: "不限",
                classui: "",
                pageid:0,     // 页码ID, 首页的pageid取值为0
                max_pageid:10, // 最大页码
            },
            users: [],    // 用户信息
            gradeList:[],

            // 信息删除相关
            isChoosedAll:false, // 是否全部选中
            delDlg:{
                isShow:false,
                tips:'是否确认删除所选用户',
                userids:null
            },

            exportDlg:{
                isShow:false,
                begin_date:null,
                end_date:null,
            },

            privileges:{}
        },
        created:function () {
            this.getGradeList();
            this.resetSearchPara()
            this.searchUser(true);
            this.checkPrivileges();
        },

        mounted:function () {

        },

        methods:{
            // 重置搜索参数
            resetSearchPara:function () {
                this.searchPara.keyword = "";
                this.searchPara.type = -1;
                this.searchPara.gradeui = "不限";
                this.searchPara.classui = "";
                this.searchPara.pageid = 0;
                this.searchPara.max_pageid = 1;
            },

            getGradeList:function () {
                let reqData = {op: "get_grade_list"};
                let param = "para="+JSON.stringify(reqData);
                new Promise(function(resolve, reject) {
                    $.ajax({
                        type:'post',
                        url:'../model/user_router.php',
                        data:param,
                        dataType:'json',
                        success:function (retData) {
                            retData.status ?
                                resolve(retData.dat): reject(retData.msg);
                        }
                    });

                }).then(function(gradeList) {
                    app.gradeList = gradeList;
                }).catch(function(errMsg) {

                });
            },

            // 查找用户
            searchUser:function(resetPage) {
                if ( resetPage ) {
                    this.searchPara.pageid = 0
                    this.searchPara.max_pageid = 0
                }
                let reqData = this.searchPara
                reqData.op = "search"
                reqData.grade = reqData.gradeui
                if ( reqData.gradeui==="不限" ) {
                    reqData.grade=""
                }
                if ( reqData.classui === "" ) {
                    reqData.class = -1;
                }
                else {
                    reqData.class = Number(reqData.classui)
                }
                reqData.vendor="school"
                let param = "para="+JSON.stringify(reqData);
                new Promise(function(resolve, reject) {
                    $.ajax({
                        type:'post',
                        url:'../model/user_router.php',
                        data:param,
                        dataType:'json',
                        success:function (retData) {
                            retData.status ? resolve(retData.dat):reject(retData.msg);
                        }
                    });

                }).then(function(jsonData) {
                    // 注意：mounted 时,无法使用this
                    app.users = jsonData.user_list
                    app.users.forEach(function(user) {
                        user.ischoosed = app.isChoosedAll
                    });
                    // 更新搜索参数
                    app.searchPara.max_pageid = jsonData.max_pageid
                }).catch(function(err) {
                    console.log('出错：' + err)
                });
            },

            checkPrivileges:function () {
                let reqData = {};
                reqData.op = "check";
                reqData.privi_names = ['xxadmin', 'jgadmin'];
                let param = "para="+JSON.stringify(reqData);
                new Promise(function(resolve, reject) {
                    $.ajax({
                        type:'post',
                        url:'../model/user_router.php',
                        data:param,
                        dataType:'json',
                        success:function (retData) {
                            if ( retData.status ) {
                                resolve(retData.dat);
                            }
                            else {
                                reject(retData.msg);
                            }
                        }
                    });

                }).then(function(privileges) {
                    app.privileges = privileges;
                    // 校外管理人员只允许创建学生账号
                    if ( privileges.xxadmin ) {
                        // app.userInfo.type = 1;
                        // app.isShowGrade = true;
                    }

                }).catch(function(errMsg) {

                });
            },

            switchPage:function(op) {
                // 回到首页,首页的pageid的取值为0
                if ( op == 0 ) {
                    this.searchPara.pageid = 0;
                }
                else {
                    this.searchPara.pageid += op;
                }
                if ( this.searchPara.pageid < 0 ) {
                    this.searchPara.pageid = 0;
                }
                else if ( this.searchPara.pageid > this.searchPara.max_pageid ) {
                    this.searchPara.pageid = this.searchPara.max_pageid;
                }
                this.searchUser(false);
            },
            // 全选或取消全选
            chooseAll:function () {
                this.isChoosedAll = !this.isChoosedAll
                this.users.forEach((user)=>{
                    user.ischoosed  = this.isChoosedAll
                })
            },

            userInfoUrl:function(userId) {
                let url = "../../userinfo.php?user=";
                url += userId;
                return url;
            },
            availableChgUrl:function(userId, isAvail) {
                let url = "../user_df_change.php?cid=";
                url += userId;
                return url;
            },

            statusDesc:function(status) {
                if ( isNull(status) || status > 4 ) {
                    status = 0;
                }
                // 0, 1, 2, 3, 4
                let descArr=['未知', '已试听', '学习中', '暂停中', '已毕业'];
                return descArr[status];
            },

            // 编辑或者添加用户信息
            editUser:function(userInfo) {
                if ( ! isNull(userInfo) ) {
                    userInfo.ischoosed = true
                    setCookie("userInfo", JSON.stringify(userInfo), 20);
                }
                window.location.href="user_post_school.php";
            },

            importUser:function () {
                window.location.href="user_import.php"
            },

            exportUser:function (okClk, cancelClk ) {
                // 添加日期格式化函数
                Date.prototype.Format = function (fmt) {
                    var o = {
                        "M+": this.getMonth() + 1, //月份
                        "d+": this.getDate(), //日
                        "h+": this.getHours(), //小时
                        "m+": this.getMinutes(), //分
                        "s+": this.getSeconds(), //秒
                        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                        "S": this.getMilliseconds() //毫秒
                    };
                    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                    for (var k in o)
                        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    return fmt;
                }

                if ( !okClk && !cancelClk ) {
                    this.exportDlg.begin_date = (new Date()).Format("yyyy-MM-dd")
                    this.exportDlg.end_date = (new Date()).Format("yyyy-MM-dd")
                    this.exportDlg.begin_date = this.exportDlg.begin_date + " 00:00"
                    this.exportDlg.end_date = this.exportDlg.end_date + " 23:59"
                    this.exportDlg.isShow = true;
                    return;
                }
                this.exportDlg.isShow = false;
                if ( cancelClk ) {
                    return;
                }
                let reqData = this.searchPara
                reqData.op = "export"
                reqData.grade = reqData.gradeui
                reqData.begin_date = this.exportDlg.begin_date
                reqData.end_date = this.exportDlg.end_date
                if ( reqData.gradeui==="不限" ) {
                    reqData.grade=""
                }
                if ( reqData.classui === "" ) {
                    reqData.class = -1;
                }
                else {
                    reqData.class = Number(reqData.classui)
                }
                let url = "../model/user_router.php?para="+JSON.stringify(reqData);
                window.location.href=url;
                //window.history.go(-1);
            },

            delUser:function (idx) {
                this.delDlg.userids = []
                if ( idx !== null ) {
                    this.users[idx].ischoosed = true
                    this.delDlg.userids.push(this.users[idx].id)
                    this.delDlg.tips="是否删除用户【"+this.users[idx].id+"】"
                }
                else {
                    this.users.forEach((user)=>{
                        if ( user.ischoosed ) {
                            this.delDlg.userids.push(user.id)
                        }
                    })
                    this.delDlg.tips="是否删除选中的所有用户"
                }
                if ( this.delDlg.userids.length <= 0 ) {
                    alert('请选择要删除的用户')
                    return
                }
                this.delDlg.isShow = true
            },

            okDelUser:function () {
                this.delDlg.isShow = false;
                // 发送删除用户请求
                let param = "para="+JSON.stringify({op:'del', userids:this.delDlg.userids})
                new Promise( (resolve, reject)=>{
                    $.ajax({
                        type:'post',
                        url:'../model/user_router.php',
                        data:param,
                        dataType:'json',
                        success:function (retData) {
                            retData.status ? resolve():reject(retData.msg)
                        }
                    })
                }).then( ()=> {
                    alert('删除用户成功')
                    app.searchUser(false)
                }).catch( (errMsg)=>{
                    alert('删除用户失败: '+errMsg+ '，特别提醒：您只能删除你所创建的用户')
                })
            },

            cancelDelUser:function () {
                this.delDlg.isShow = false;
                this.users.forEach((user)=>{
                    user.ischoosed  = false
                })
                this.isChoosedAll = false
            },
        }
    });
</script>

</body>
</html>
<?php
//require("../oj-footer.php");
?>
